package com.qing.picture.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qing.picture.constant.UserConstant;
import com.qing.picture.exception.BusinessException;
import com.qing.picture.exception.ErrorCode;
import com.qing.picture.manager.auth.StpKit;
import com.qing.picture.mapper.UserMapper;
import com.qing.picture.model.dto.user.UserLoginRequest;
import com.qing.picture.model.dto.user.UserQueryRequest;
import com.qing.picture.model.dto.user.UserRegisterRequest;
import com.qing.picture.model.entity.User;
import com.qing.picture.model.enums.UserRoleEnum;
import com.qing.picture.model.vo.LoginUserVo;
import com.qing.picture.model.vo.UserVo;
import com.qing.picture.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.qing.picture.constant.UserConstant.USER_LOGIN_STATE;

/**
* @author 86157
* @description 针对表【user(用户)】的数据库操作Service实现
* @createDate 2025-03-14 16:17:11
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Override
    public LoginUserVo userLogin(UserLoginRequest userLoginRequest, HttpServletRequest request) {
//        1. 校验数据
        // 2. 加密
        String encryptedPassword = getEncryptPassword(userLoginRequest.getUserPassword());
        // 3. 查询用户信息
        User user =this.baseMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUserAccount, userLoginRequest.getUserAccount()).eq(User::getUserPassword, encryptedPassword));
        if(user==null){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"账号不存在或密码错误");
        }
        LoginUserVo loginUserVO = getLoginUserVO(user);
        //存储用户信息
        request.getSession().setAttribute(USER_LOGIN_STATE,loginUserVO);

        // 4. 记录用户登录态到 Sa-token，便于空间鉴权时使用，注意保证该用户信息与 SpringSession 中的信息过期时间一致
        StpKit.SPACE.login(user.getId());
        StpKit.SPACE.getSession().set(USER_LOGIN_STATE, user);

        return loginUserVO;
    }

    @Override
    public boolean userLogout(HttpServletRequest request) {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        if (userObj == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "未登录");
        }
        // 移除登录态
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return true;
    }

    @Override
    public User getLoginUser(HttpServletRequest request) {
        // 判断是否已经登录
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        LoginUserVo currentUser = (LoginUserVo) userObj;
        if (currentUser == null || currentUser.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        // 从数据库中查询（追求性能的话可以注释，直接返回上述结果）
        Long userId = currentUser.getId();
        User user = this.getById(userId);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return user;
    }
    /**
     * 获取脱敏类的用户信息
     *
     * @param user 用户
     * @return 脱敏后的用户信息
     */
    @Override
    public LoginUserVo getLoginUserVO(User user) {
        if (user == null) {
            return null;
        }
        LoginUserVo loginUserVO = new LoginUserVo();
        BeanUtil.copyProperties(user, loginUserVO);
        return loginUserVO;
    }
    @Override
    public User userRegister(UserRegisterRequest request) {
        // 1. 校验数据
        // 2. 查重
        Long user =this.baseMapper.selectCount(new LambdaQueryWrapper<User>().eq(User::getUserAccount, request.getUserAccount()));
        if(user>0){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"用户已存在");
        }
        // 3. 加密密码
        String encryptedPassword = getEncryptPassword(request.getUserPassword());
        // 4. 保存用户信息
        User userEntity = new User();
        userEntity.setUserAccount(request.getUserAccount());
        userEntity.setUserPassword(encryptedPassword);
        userEntity.setUserName("无名氏");
        userEntity.setUserRole(UserRoleEnum.USER.getValue());
        boolean save = this.save(userEntity);
        if(!save){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"注册失败数据库错误");
        }

        return userEntity;
    }

    @Override
    public String getEncryptPassword(String userPassword) {
        // 盐值，混淆密码
        final String SALT = "qing";
        return DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
    }

    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = userQueryRequest.getId();
        String userAccount = userQueryRequest.getUserAccount();
        String userName = userQueryRequest.getUserName();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq(ObjUtil.isNotNull(id)&&id>=0, "id", id);
        queryWrapper.eq(StrUtil.isNotBlank(userRole), "userRole", userRole);
        queryWrapper.like(StrUtil.isNotBlank(userAccount), "userAccount", userAccount);
        queryWrapper.like(StrUtil.isNotBlank(userName), "userName", userName);
        queryWrapper.like(StrUtil.isNotBlank(userProfile), "userProfile", userProfile);
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    @Override
    public List<UserVo> getUserVOList(List<User> userList) {
        if (CollUtil.isEmpty(userList)) {
            return new ArrayList<>();
        }
        List<UserVo> userVoList = userList.stream().map(user -> {
            UserVo userVo = new UserVo();
            BeanUtil.copyProperties(user, userVo);
            return userVo;}).collect(Collectors.toList());
        return userVoList;
    }

    /**
     * 判断是否是管理员
     * @param user 用户
     * @return true 是管理员，false 不是管理员
     * @author 86157
     */
    @Override
    public boolean isAdmin(User user) {
        return user != null && UserRoleEnum.ADMIN.getValue().equals(user.getUserRole());
    }

    /**
     * 获得脱敏后的用户信息
     *
     * @param user
     * @return
     */
    @Override
    public UserVo getUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVo userVO = new UserVo();
        BeanUtil.copyProperties(user, userVO);
        return userVO;
    }
}




